//
//  SaveFile.m
//  GIFShow
//
//  Created by lanou11air029 on 15/4/15.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "SaveFile.h"
#import "AppDelegate.h"
#import "GifModel.h"
@interface SaveFile ()
@property (nonatomic, strong) NSManagedObjectContext * managedContext;

//@property (nonatomic) BOOL oneOrMore;
@end
@implementation SaveFile
+(instancetype)shareFile{
    static SaveFile * saveManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        saveManager = [[SaveFile alloc]init];
    });
    return saveManager;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        self.managedContext = appDelegate.managedObjectContext;
    }
    return self;
}
-(void)saveGifItem:(GifModel *)gifModel{
        GifDownload * gifItem = [self getGifItemWithArt_id:gifModel.art_id];
        if (gifItem == nil) {
            NSEntityDescription * gifDED = [NSEntityDescription entityForName:@"GifDownload" inManagedObjectContext:self.managedContext];
            GifDownload * gifItem = [[GifDownload alloc]initWithEntity:gifDED insertIntoManagedObjectContext:self.managedContext];
            gifItem.art_id = gifModel.art_id;
            gifItem.content = gifModel.content;
            gifItem.collection = gifModel.comment_sum;
            gifItem.ding = gifModel.ding;
            gifItem.date = gifModel.pub_time;
            CGFloat width = [[[gifModel.imagelist valueForKey:@"thumb_w"] lastObject] floatValue];
            CGFloat height = [[[gifModel.imagelist valueForKey:@"thumb_h"] lastObject] floatValue];
            gifItem.width = [NSNumber numberWithFloat:width];
            gifItem.height = [NSNumber numberWithFloat:height];

            gifItem.username = [gifModel.userinfo objectForKey:@"nickname"];
            
            NSString * thumbStr = [gifModel.imagelist.lastObject valueForKey:@"thumb"];
            gifItem.mainImageUrl = [thumbStr stringByReplacingOccurrencesOfString:@"thumb" withString:@"large"];
            gifItem.title = [gifModel.userinfo objectForKey:@"nickname"];
            gifItem.userHeadIconUrl = [gifModel.userinfo objectForKey:@"avatar"];
            [self save];
        }
}
-(void)saveGifItemGif:(NSString *)gifKey WithArt_id:(NSString *)art_id{
    
}

-(GifDownload *)getGifItemWithArt_id:(NSString *)art_id{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"GifDownload" inManagedObjectContext:self.managedContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"art_id = %@", art_id];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"art_id"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"查询失败 error = %@",error);
    }else if (fetchedObjects.count == 1){
        NSLog(@"查询成功！");
    }
    return fetchedObjects.lastObject;
}
// 红桃
-(void)dingGifItemWithArt_id:(NSString *)art_id{
    GifDownload * gifItem = [self getGifItemWithArt_id:art_id];
//    gifItem.ding
    if (gifItem == nil) {
        return;
    }
    if (gifItem.isding.boolValue != YES) {
        gifItem.isding = [NSNumber numberWithBool:YES];
        gifItem.ding = [NSString stringWithFormat:@"%ld",(long)gifItem.ding.integerValue+1];
        [self save];
    }
}
// 五角星
-(void)favGifItemWithArt_id:(NSString *)art_id{
    GifDownload * gifItem = [self getGifItemWithArt_id:art_id];
    //    gifItem.Collection
    if (gifItem == nil) {
        return;
    }
    if (gifItem.iscollection.boolValue != YES) {
        gifItem.iscollection = [NSNumber numberWithBool:YES];
        gifItem.ding = [NSString stringWithFormat:@"%ld",(long)gifItem.collection.integerValue+1];
        [self save];
    }
}
-(void)downloadGifItemWithArt_id:(NSString*)art_id{
    GifDownload * gifItem = [self getGifItemWithArt_id:art_id];
    //    gifItem.Download
    if (gifItem == nil) {
        return;
    }
    if (gifItem.isdownload.boolValue != YES) {
        gifItem.isdownload = [NSNumber numberWithBool:YES];
        [self save];
    }
}
-(BOOL)isDingWithArt_id:(NSString *)art_id{
    GifDownload * gifItem = [self getGifItemWithArt_id:art_id];

    return gifItem.isding.boolValue;
}
-(BOOL)isFavWithArt_id:(NSString *)art_id{
    GifDownload * gifItem = [self getGifItemWithArt_id:art_id];
 
    return gifItem.iscollection.boolValue;
}
-(NSArray *)getAllCollectionGifs{
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"iscollection = %@",[NSNumber numberWithBool:YES]];
    NSArray * array = [self getGifItemsWithPredicate:predicate];
    return array;
}
-(NSArray *)getAllDownloadGifs{
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"isdownload = %@",[NSNumber numberWithBool:YES]];
    NSArray * array = [self getGifItemsWithPredicate:predicate];
    return array;}
-(NSArray *)getGifItemsWithPredicate:(NSPredicate *)predicate{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"GifDownload" inManagedObjectContext:self.managedContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"art_id"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"查询失败 error = %@",error);
    }else if (fetchedObjects.count > 0){
        NSLog(@"查询成功");
    }
    return fetchedObjects;
}
-(BOOL)save{
    NSError * saveError = nil;
    [self.managedContext save:&saveError];
    if (saveError) {
        NSLog(@"保存出错 error = %@",saveError);
        return NO;
    }
    return YES;
}
@end
